<!DOCTYPE html>
<html>
<head>
	<title>手机网页聊天室</title>
	<meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
	<link rel="stylesheet" id="csn-css-7ui" type="text/css" href="__HOME__/css/7ui.min.css">
</head>
<style>
	/*头部样式*/
	.top{font-size: 0.72rem; height: 1.5rem;background: #0EA9EB;text-align: center;line-height: 1.5rem;color: #fff;position: fixed;width: 100%;z-index: 9;}
	.num{font-size: 0.04rem;height: 1rem;background: url('/static/home/img/chat/more.png') no-repeat left / 0.4rem;text-align: right;padding-left: 0.5rem}
	.back{display: inline-block;width: 1rem;height: 1rem;background: url('/static/home/img/chat/back.png') no-repeat center / 1rem;float: left;margin:0.2rem;}
	.member{display: inline-block;width: 1rem;height: 1rem;background: url('/static/home/img/chat/people.png') no-repeat center / 1rem;float: right;margin:0.2rem;}

	/*内容框样式*/
	.content{width: 100%;height: 23rem;padding-top: 1.5rem;overflow-y: auto;overflow-x:hidden;}
	.msg-tb{width:14rem;margin:0.6rem auto 0;margin-bottom: 0.56rem;}
	.msg-head{vertical-align:top;width:2rem;text-align:center;}
	.msg-head img{width:2rem;height:2rem;border-radius: 50%;}
	.msg-title{font-size:0.48rem;color: #743283;}
	.msg-me .msg-title,.msg-me .msg-text{text-align:right;}
	.msg-text{padding:0.4rem 0;font-size: 0.56rem}
	.msg-text span{display:inline-block;max-width:14rem;padding:0.4rem;border-radius:0.2rem;word-break:break-all;text-align:left;cursor:pointer}
	.msg-text img{max-width: 5rem;}
	.msg-other .msg-text span{background:#ccc;}
	.msg-me .msg-text span{background:#abc;}
	.tip{font-size: 0.48rem;color: #969292;text-align: center;}

	/*底部发送消息样式*/
	.footer{height: 1.7rem;background: #e8e8e8;position: fixed;width: 100%;bottom: 0;line-height: 1.7rem;}
	.emoji{width: 1rem;height: 1rem;border:none;background: url('/static/home/img/chat/emoji.png') no-repeat center / 1rem;margin:0.3rem 0.1rem;float: left;cursor: pointer;}
	.pic{width: 1rem;height: 1rem;border:none;background: url('/static/home/img/chat/pic.png') no-repeat center / 1rem;margin:0.3rem 0.1rem;float: left;cursor: pointer;}
	.message{width: 9rem;height: 1.1rem;padding:0.1rem;border:none;float: left;margin:0.15rem;font-size: 0.56rem;}
	.send{width: 2.5rem;height: 1.3rem;border:none;background: #0EA9EB;text-align: center;font-size: 0.56rem;color: #fff;line-height: 1rem;float: left;margin:0.15rem 0.2rem;cursor: pointer;}
	.air{width: 100%;height: 2rem;}

	/*表情*/
	.emoji_div{position: fixed;bottom: 2rem;padding-left: 0.2rem;opacity: 0;}
	.emoji_div tr td img {width: 1rem;height: 1rem;}
	.emoji_div tr td{padding: 0.2rem;}
	/*显示大图*/
	.big_img{width:100%;height:100%;background-color:rgba(0,0,0,0.5);position: fixed;z-index: 99;text-align: center;top: 0;left: 0;}
	.tag_img{cursor: pointer;}
	.big_img img {max-width: 15rem;max-height: 22rem;}

	/*更多选择*/
	.msg_more,.right-click{position:fixed;background:#fff;border:0.04rem solid #c5c2c2;border-radius:0.2rem}
    .msg_more li,.right-click li{font-size: 0.56rem; text-align: center;border-bottom:0.04rem solid #eee;padding:0.4rem 0.8rem;cursor:pointer;color: #7b7575}
    .msg_more li:hover,.right-click li:hover{color:#5d5959}
    .msg_more li:last-child{border-bottom:none}
</style>
<body>
<!-- 头部 -->
<header class="top">
	<a href="{:url('Index/select_user')}" class="back"></a>
	<span>聊天室</span>
	<span class="num"><b id="count"></b>人在线</span>
	<a href="#" class="member"></a>
</header>

<!-- 聊天室界面 -->
<div class="content" id="content_show"></div>
<!-- 表情 -->
<div class="emoji_div csn-hide"></div>
<!-- 图片选择 -->
<div class="img" style="display: none;">
	<input type="file" onchange="upload_img(this.files[0])" id="select_img" hidden>
</div>
<!-- 显示大图 -->
<div class="big_img" style="display: none;">
    <img src="">
</div>
<!-- 空气墙 -->
<div class="air"></div>
<!-- 底部发送消息 -->
<div class="footer">
	<button class="emoji"></button>
	<button class="pic"></button>
	<input class="message" type="text" placeholder="请输入聊天信息">
	<!-- <div class="message" contenteditable="true"></div> -->
	<button class="send" onclick="send_msg()">发送</button>
</div>
</body>
<script src="__HOME__/js/7ui.min.js"></script>
<script src="__HOME__/js/clipboard.min.js"></script>
<script>
	// 初始化rem
	_7ui(function() {
        _7ui.rem();
		showEmoji();
    });

	// 去掉默认的鼠标右键事件
	$(function () {
	    $(document).on('contextmenu', function(e) {
	        e.preventDefault();
	    });
	});

	// 消息记录
	var _msg_list = window.localStorage.getItem('msg_list');

    // 内容对象
    var div = document.getElementById('content_show');

    // 图片选择器
    var _select_img = document.getElementById('select_img');

	// 当前选择的用户ID
	{if condition="$uid"}var uid = {$uid}{else /}var uid = 1{/if};

	// 获取输入框对象
	var user_input = document.getElementsByClassName("message")[0];
	// 默认输入框焦点
	user_input.focus();

	// 接收服务器的消息
	(window.ws = new WebSocket("ws://119.27.191.150:9502")).onmessage = function (e) {
	    showMsg(e.data)
	};

	ws.onopen = function (evt) {
	    if(ws.readyState === 1){
			ws.send('{"type":"u","u":"用户登录","uid":"'+uid+'"}');
		}
	};

	// 提示模板
	var tip_tpl = '<table class="msg-tb msg-other"><tbody><tr><td class="tip">{msg}</td></tr></tbody></table>';

	// 个人消息模板
	var own_tpl = '<table class="msg-tb msg-me"><tbody><tr><td class="msg-title">用户{name}</td><td rowspan="2" class="msg-head"><img src="/static/home/img/chat/header{head}.jpg" alt=""></td></tr><tr><td class="msg-text"><span class="msg-span" token="{token}" data-type="{type}"><div class="t_div">{content}</div></span></td></tr></tbody></table>';

	// 其他人消息模板
	var other_tpl = '<table class="msg-tb msg-other"><tbody><tr><td class="msg-head" rowspan="2"><img src="/static/home/img/chat/header{head}.jpg" alt=""></td><td class="msg-title">用户{name}</td></tr><tr><td class="msg-text"><span class="msg-span" token="{token}" data-type="{type}"><div class="t_div">{content}</div></span></td></tr></tbody></table>';

	// 显示消息
	function showMsg(msg){
		var data = JSON.parse(msg);
		var str = '';
		if(data.type == 'm'){
			// 如果是提示消息，则显示提示文本
			str += tip_tpl.replace('{msg}',data.c).replace('{type}',data.type);
			// 修改在线人数
			$("#count").html(data.count);
		}else if (data.type == 'l') {
			// 显示消息记录
			for (var m = data.log.length - 1; 0 <= m; m--) {
				var message = JSON.parse(data.log[m]);
				if(message.type == 't' || message.type == 'i'){
					var tp = other_tpl;
					str += message.type === 't' ? tp.replace('{content}',resolve_emoji(message.t)).replace('{name}',message.from).replace('{head}',message.from).replace('{type}',message.type).replace('{token}',message.token) : tp.replace('{content}',"<img class='tag_img' src='"+message.i+"' title='点击查看大图'>").replace('{name}',message.from).replace('{head}',message.from).replace('{type}',message.type).replace('{token}',message.token);
				}
			}
		}else if (data.type == 't' || data.type == 'i') {
			var tp = data.me ? own_tpl : other_tpl;
			str = data.type === 't' ? tp.replace('{content}',resolve_emoji(data.t)).replace('{name}',data.from).replace('{head}',data.from).replace('{type}',data.type).replace('{token}',data.token) : tp.replace('{content}',"<img class='tag_img' src='"+data.i+"' title='点击查看大图'>").replace('{name}',data.from).replace('{head}',data.from).replace('{type}',data.type).replace('{token}',data.token);
			// 存储消息
			localStorage.setItem("msg_list",data);
		}else if (data.type == 'b') {
			// 撤回消息
			var obj = document.getElementsByClassName('msg-span');
			for(var a = 0; a < obj.length; a++){
				if(obj[a].getAttribute('token') === data.b){
					$('#content_show > .msg-tb').eq(a).remove();
				}
			}
			// 提示用户已撤回
			str = tip_tpl.replace('{msg}',data.c).replace('{type}',data.type);
		}
		// 在内容框里追加
		$("#content_show").append(str);
		// 让滚动条始终在最后
    	div.scrollTop = div.scrollHeight;
    	// 点击查看大图
    	$('.msg-span').eq(-1).on('click', function (e) {
            if ($(this).attr('data-type') !== 'i') return;
            e.stopPropagation();
            $('.msg_more').remove();
            $(".big_img").find('img').attr('src', $(this).find('.tag_img').attr('src'));
            $(".big_img").show();
        }).on('touchstart',function(e){
        	var token = $(this).attr('token');
        	timeOutEvent = setTimeout(function(){
	          //此处为长按事件-----在此显示遮罩层及删除按钮
	          var evt = e.touches[0];
	          openMsgMore(evt.clientX, evt.clientY,token);
	        },500);
        })
	}

	// 显示更多操作
	function openMsgMore(x, y, token) {
	    $('.msg_more').remove();
	    $('body').append('<ul class="msg_more" style="top:' + (y + 25) + 'px;left:' + (x + 10) + 'px;">' + '<li onclick="withdrawMessage(\'' + token + '\');">撤回</li><li onclick="copyMessage(\'' + token + '\');">复制</li></ul>');
	}

	// 撤回消息
	function withdrawMessage(token)
	{
		if(token === '') return _7ui.info('该条消息不存在');
		if(!uid) return _7ui.info('请先登录');
		// 向socket服务器发送撤回请求
		ws.send('{"type":"c","c":"'+token+'","uid":"'+uid+'"}');
	}

	// 复制消息到粘贴板
	function copyMessage(token)
	{
		var obj = document.getElementsByClassName('msg-span');
		for(var a = 0; a < obj.length; a++){
			if(obj[a].getAttribute('token') === token){
				console.log(obj[a].firstChild)
			}
		}
	}

	// 显示表情
	$(".emoji").on('click',function(e){
		$.stop(e,1);
		if($(".emoji_div").hasCls('csn-hide')){
			$(".emoji_div").rmCls('csn-hide').show();
		}else{
			$(".emoji_div").hide().delay(function() {
				$(".emoji_div").addCls('csn-hide');
			}, 20);
		}
	})

	// 点击空白除隐藏
	$(document).on('click',function(){
        $(".msg_more").remove();
        $(".right-click").remove();
		$(".big_img").hide();
		$(".emoji_div").hide().delay(function() {
			$(".emoji_div").addCls('csn-hide');
		}, 20);
	})

	// 输出表情
	function showEmoji(){
		var row = 6,col = 12;
		var str = '<table class="biaoqing">';
		for(var i = 0; i <= row; i++){
			str += '<tr>';
			for(var j = 0; j <= col; j++){
				var n = i * col + j;
				str += '<td>' + (n < 72 ? "<img onclick='select_emoji("+n+")' src='/static/home/img/face/"+n+".gif'>" : '') + '</td>';
			}
			str += '</tr>';
		}
		str += '</table>';
		$(".emoji_div").html(str);
	}

	// 选中表情
	function select_emoji(n){
		cursorInsert(user_input,'{{@'+n+'}}');
	}

	// 模拟点击选择图片事件
	$(".pic").on('click',function(){
		_select_img.click();
	})

	// 在光标处插入内容
	function cursorInsert(obj,txt){
		if(document.selection){
			// 默认选中的话直接插入文本
			obj.selection.createRange().text = txt;
		}else{
			// 如果未选中,则选中输入框的光标，并在光标开的地方插入文本
			var v = obj.value;
	        var i = obj.selectionStart;
	        obj.value = v.substr(0, i) + txt + v.substr(i);
	        user_input.focus();
	        obj.selectionStart = i + txt.length;
		}
	}

	// 图片上传
	function upload_img(f){
		// 判断图片是否超出1M，是否是jpg，png，gif格式
		if(f.type.substr(0,6) !== 'image/') return _7ui.info('请上传jpg,png,gif等图片文件');
		var size = f.size / 1024 / 1024;
		if(size > 1) return _7ui.info('请上传小于1M的图片');
		_7ui.upload('/home/Index/send_chat_img', {file_img: f}, function (e) {
	        var json = JSON.parse(e);
	        if (json.status == 0) {
	            _7ui.info(json.msg);
	        } else {
	            ws.send('{"type":"i", "i":"' + json.img + '","uid":'+uid+'}');
	            user_input.value = '';
	            user_input.focus();
	        }
	        $("#select_img").val('');
	    });
	}

	// 解析表情
	function resolve_emoji(txt){
		var rule = /{{@(\d|[1-6]\d|7[01])}}/;
		if(rule.test(txt)){
			// 如果匹配到了，则替换为图片
			return resolve_emoji(txt.replace(rule,"<img src='/static/home/img/face/$1.gif'>"));
		}else{
			return txt;
		}
	}

	// 用户发送消息
	function send_msg(){
		var msg = $(".message").val();
		if(msg == '') return _7ui.info('发送的消息不能为空');
		sendMsg({type:'t','t':msg},function(){
			user_input.value = '';
			user_input.focus();
		})
	}

	// 发送消息
	function sendMsg(msg, func){
		if(uid){
			msg['uid'] = uid;
			ws.send(JSON.stringify(msg));
			func && func();
		}else{
			_7ui.confirm({
                t: '请先选择角色', i: '您还未有角色，请先选择角色', fn: function (e) {
                    location.href="/home/Index/select_user";
                }
            })
		}
	}
</script>
</html>